import { createRouter, createWebHashHistory } from "vue-router";
import platformRouter from "./modules/platform.js";
import { ElMessage } from "element-plus";

var routerArr = platformRouter;

// const routes = routerArr[store.getters.homePath + "Router"];
const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: routerArr,
});
// 全局前置守卫
router.beforeEach(async (to, from, next) => {
  // 获取token
  const hasToken = sessionStorage.getItem("token");
  if (hasToken) {
    if (to.path === "/login") {
      // 如果已登录，访问登录页则重定向到首页
      next("/admin");
    } else {
      // 检查路由是否需要权限
      if (to.meta && to.meta.requiresAuth) {
        // 权限验证逻辑
        next();
      } else {
        next();
      }
    }
  } else {
    if (to.path === "/login") {
      next();
    } else {
      ElMessage({
        message: "请重新登录",
        type: "error",
      });
      next("/login");
    }
  }
});

router.onError((error) => {
  const pattern = /Loading chunk (\d)+ failed/g;
  const isChunkLoadFailed = error.message.match(pattern);
  const targetPath = router.options.history.location;
  if (isChunkLoadFailed) {
    router.replace(targetPath);
  } else {
    ElMessage({
      message: "网页无响应",
      type: "error",
    });
    // window.location.reload()
  }
});

export default router;
